#!/bin/bash
HelpMessages () {
    echo "$0:          Record the debugging results"
    echo "command:  sm [-h] help messages"
    echo "             [-s|--success]: debugged successfully, default failed"
    echo "             [-m|--message ]: messages"
    echo "             [-f|--finish ]: finish this job"
    echo "             [-c|--current ] vim current log file"
}

config=~/.wsconfig
dateTime=`date "+%Y-%m-%d %H:%M:%S"`
currentDir=`pwd`
recordFile=`grep "recordFile" $config | cut -d " " -f 3`
baseJobName=`grep "baseJobName" $config | cut -d " " -f 3`
root_dir=`grep "root_dir" $config | cut -d " " -f 3`

stat="No"
success="Failed"
note="..."
ARGS=`getopt -o hsfcm: --long success,finish,message: -n 'example.sh' -- "$@"`
brace=""
position=middle

if [ $? != 0 ]; then
     echo "Terminating..."
     exit 1
fi
eval set -- "${ARGS}"

while true
do
#    echo "first $1, second is $2"
    case "$1" in
        -h|--help)
            HelpMessages;
            exit 1
            shift
            ;;
        -s|--success)
            success="SUCCESS"
            shift
            ;;
        -f|--finish)
            brace="}"
            shift
            ;;
        -c|--current)
            stat="Yes"
            shift
            ;;
        -m|--message)
            note="$2"
            shift 2
            ;;
         --)
            shift
            break
            ;;
         *)
            echo "Internal error"
            exit 1
    esac
done

job=`ls ${baseJobName}* -t | cut -d ' ' -f 1 | head -1`
jobID=`ls out* -t | cut -d ' ' -f 1 | head -1 | cut -d "." -f 2`
logID=`grep -n "logID=" $job | cut -d "=" -f 2`
logFile="${root_dir}/log/${logID}.log"

if [ ${stat} = "Yes" ]; then
    vim ${logFile}
    exit 1
fi

lineNumber=`grep -n "jobID ${jobID}:" ${logFile} | cut -d : -f 1`

dirName=`pwd | sed 's,^\(.*/\)\?\([^/]*\),\2,'`
sed -i "${lineNumber}i${dirName}, jobID ${jobID}: ${note}, ${success}. " $logFile

lineNumber=`expr $lineNumber + 1`
sed -i "${lineNumber}d" $logFile

if [ "${brace}" = "}" ]; then
    lastLine=`tail -1 $logFile`
    lineNumber=`sed -n '$=' $logFile`
    sed -i "${lineNumber}i${lastLine} ${brace}" $logFile
    lineNumber=`expr $lineNumber + 1`
    sed -i "${lineNumber}d" $logFile
    echo "" >> $logFile
   
    cat $recordFile >> $logFile
    cp -f $logFile $recordFile
    rm -f $logFile
fi

